package pl.edu.agh.iosr.gamblingzone.userpanel.action;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import static org.jboss.seam.ScopeType.EVENT;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.faces.FacesMessages;

import pl.edu.agh.iosr.gamblingzone.dao.UserDAO;
import pl.edu.agh.iosr.gamblingzone.dao.ejb.UserDAOBean;
import pl.edu.agh.iosr.gamblingzone.model.User;
import pl.edu.agh.iosr.gamblingzone.utils.DAOFactory;
import pl.edu.agh.iosr.gamblingzone.utils.UserValidator;

@Stateful
@Scope(EVENT)
@Name("changePassword")
@Restrict("#{identity.loggedIn}")
public class ChangePasswordAction implements ChangePassword {
	@In
	@Out
	private User user;

	@PersistenceContext
	private EntityManager em;
	
	@In(required=true)
	DAOFactory dao;

	private String newPwd;
	private String newPwdVerify;
	private boolean changed;

	@In
	private FacesMessages facesMessages;

	public void changePassword() {
		if (!UserValidator.isUserNewPwdDifferent(user, newPwd)) {
			facesMessages.addToControl("newPwdVerify",
					"New password has to be different");
			resetFields();
		} else if (newPwd != null
				&& !UserValidator.isUserPwdInProperLength(newPwd)) {
			facesMessages.addToControl("newPwdVerify",
					"Length between 5 and 15");
			resetFields();
		} else if (newPwd != null && newPwd.equals(newPwdVerify)) {
			user.setPassword(newPwd);
			user = em.merge(user);
			facesMessages.add("Password updated");
			changed = true;
		} else {
			facesMessages.addToControl("newPwdVerify", "Re-enter new password");
			revertUser();
			resetFields();
		}
	}

	public boolean isChanged() {
		return changed;
	}

	private void revertUser() {
		UserDAO userDAO = dao.getUserDAO();

		user = userDAO.findByLogin(user.getLoginName());
	}

	public String getNewPwdVerify() {
		return newPwdVerify;
	}

	public void setNewPwdVerify(String newPwdVerify) {
		this.newPwdVerify = newPwdVerify;
	}

	public String getNewPwd() {
		return newPwd;
	}

	public void setNewPwd(String newPwd) {
		this.newPwd = newPwd;
	}

	private void resetFields() {
		newPwdVerify = null;
		newPwd = null;
	}

	@Remove
	public void destroy() {
	}
}
